let span_account = document.getElementById("span_account");
let acc_account = sessionStorage.getItem("account");
span_account.innerText = acc_account;

let books = [{
		id: 1,
		name: '三国演义',
		tdate: '1899-08-09',
		price: '60.00',
		count: 1,
		account: "hh"
	},
	{
		id: 2,
		name: '水浒传',
		tdate: '1863-09-10',
		price: '69.00',
		count: 1,
		account: "haha"
	},
	{
		id: 3,
		name: '红楼梦',
		tdate: '1884-03-12',
		price: '99.00',
		count: 1,
		account: "aa"
	},
	{
		id: 4,
		name: '西游记',
		tdate: '1900-07-28',
		price: '9.00',
		count: 1,
		account: "aa"
	}
];

//将数组保存到sessionStrage中
//查看参数有没有
let data = localStorage.getItem("data");
if (data) {
	//转译处理
	books = JSON.parse(data);
} else {
	localStorage.setItem("data", JSON.stringify(books));
}

//获取table对象
let table = document.getElementsByTagName("table")[0];
let tbody = table.getElementsByTagName("tbody")[0];

let ipt_name = document.getElementById("ipt_name");
let ipt_low = document.getElementById("ipt_low");
let ipt_top = document.getElementById("ipt_top");

function search() {
	let name = ipt_name.value; //获取书名
	let low = ipt_low.value; //获取最低价
	let top = ipt_top.value; //获取最低价
	if (name.trim().length === 0 || low.trim().length == 0 && top.trim().length === 0) {
		alert("请输入查询条件")
		return;
	}
	clear();
	update({
		name,
		low,
		top
	});
	getTotal({
		name,
		low,
		top
	});
}

function clear() {
	do {
		tbody.removeChild(tbody.firstChild);
	} while (tbody.hasChildNodes());
}

update();
getTotal();

//将数组中的值显示在表格中
function update(args) {
	for (let index in books) {
		let item = books[index];
		//嵌套地狱：来个if或switch来个18层嵌套
		//账号与书本之间的关联处理
		if (item.account !== acc_account) {
			continue;
		}

		//搜索功能
		if (args) {
			if (item.name.trim().length !== 0 && item.name !== args.name) {
				continue;
			}
			if (item.low.trim().length !== 0 && item.price < args.low) {
				continue;
			}
			if (item.top.trim().length !== 0 && item.price > args.top) {
				continue;
			}
		}

		let tr = document.createElement("tr");
		let chb = `
			<input type="checkbox" name="aa"/>
		`;
		appendTd(tr, chb, true);
		tbody.appendChild(tr);

		for (let val in item) {
			if (val === "account") {
				continue;
			}
			let text = item[val];
			let isHtml = false;
			//val ==== 书名 就是一个超链接，进行跳转
			if (val === "name") {
				text = `
					<a  href='#' onclick='edit(${index})'>${text}</a>
				`;
				isHtml = true;
			} else if (val === 'count') {
				text =
					`
					<button type="button" onclick="reduce(${index})">-</button>
					<span>${text}</span>
					<button type="button" onclick="pluscount(${index})">+</button>
				`
				isHtml = true;
			}
			appendTd(tr, text, isHtml);
		}
		let opt = `
			<button onclick="edit(${index})">编辑</button>
			<button onclick="del(${index})">删除</button>
		`;
		appendTd(tr, opt, true);
	}
}

function appendTd(tr, value, isHtml) {
	let td = document.createElement("td");
	if (isHtml) {
		td.innerHTML = value;
	} else {
		td.innerText = value;
	}
	tr.appendChild(td);
}

//总价格
function getTotal(args) {
	let total = 0;
	//遍历数组
	for (let item of books) {
		if (item.account !== acc_account) {
			continue;
		}
		//搜索功能
		if (args) {
			if (args.name.trim().length !== 0 && item.name !== args.name) {
				continue;
			}
			if (args.low.trim().length !== 0 && item.price < args.low) {
				continue;
			}
			if (args.top.trim().length !== 0 && item.price > args.top) {
				continue;
			}
		}
		total += item.price * item.count;
	}
	document.getElementById("span_result").innerText = total;
}

//跳转页面
function add() {
	location.href = "添加书本页面.html";
	sessionStorage.setItem("item", null);
}
//加
function pluscount(index) {
	let item = books[index];
	item.count++;
	let node = tbody.childNodes[index + 1];
	let span = node.getElementsByTagName("span")[0];
	span.innerText = item.count;
	getTotal();
}

//减
function reduce(index) {
	let item = books[index];
	if (item.count === 1) {
		return;
	}
	item.count--;
	let node = tbody.childNodes[index + 1];
	let span = node.getElementsByTagName("span")[0];
	span.innerText = item.count;
	getTotal();
}
//编辑
function edit(index) {
	let item = books[index];
	// item.index = index;
	//你要编辑哪一条，就把哪一条里面的对象，就保存到setItem中
	sessionStorage.setItem("index", index);
	sessionStorage.setItem("item", JSON.stringify(books[index]));
	location.href = "添加书本页面.html";
}

//删除
function del(index) {
	let result = confirm("确认是否删除" + books[index].name + "这本书？");
	console.log(result);
	if (!result) {
		return;
	}
	//删除数组中的数据
	books.splice(index, 1);
	clear();
	update();
	//更新到localStorage
	localStorage.setItem("data", JSON.stringify(books));
	//更新价格
	getTotal();
}
//点击全选 全部选中
$(".seleAll").on('click', function() {
	var seleAll = $("input[type='checkbox']")
	seleAll.each(function() {
		seleAll.prop('checked', true)
	})
})
// 反选
$(".reverse").on("click", function() {
	var seleAll = $("input[type='checkbox']")
	seleAll.each(function() {
		this.checked = !this.checked
	})
})

//全不选
$(".noneSele").on("click", function() {
	var seleAll = $("input[type='checkbox']")
	seleAll.each(function() {
		seleAll.prop('checked', false)
	})
})

//批量删除
$(".allDel").on("click", function(index) {
	var allDel = $(":checkbox:checked")
	if (allDel.length > 0) {
		allDel.each(function() {
			books.splice(index, 1);
		})
		clear();
		update();
		//更新到localStorage
		localStorage.setItem("data", JSON.stringify(books));
		//更新价格
		getTotal();
		// console.log(books);
	} else {
		alert('请选中数据后在删除')
	}
	getTotal();
})
function downFile() {
	var elementA = document.createElement('a');

	elementA.setAttribute('href', 'data:text/plain;charset=utf-8,' + JSON.stringify(books[index]));
	elementA.setAttribute('download', +new Date() + ".tpl");
	elementA.style.display = 'none';
	document.body.appendChild(elementA);
	elementA.click();
	document.body.removeChild(elementA);
}